<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;" name="viewport" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        *{
            margin:0;
            padding: 0;
        }
        body {
            /* background: skyblue; */
            text-align: center;
        }
        button{
            display: block;
            border:2px solid #cccccc;
            height: 30px;
            width: 100%;
        }
        #myCanvas2{
            border:1px solid black;
        }
    </style>
</head>

<body>
    <canvas id="myCanvas"></canvas>
    <script>
        var ctx
        appCanvas();
        function appCanvas() {
            var winW = window.innerWidth;
            var myCanvas = document.getElementById('myCanvas');
            myCanvas.width = winW * 1;
            myCanvas.height = winW * 1;
            var myCanW = myCanvas.width;
            var myCanH = myCanvas.height;
            if (!myCanvas || !myCanvas.getContext) {
                return
            };
            ctx = myCanvas.getContext("2d");
            ctx.fillStyle="rgba(0,0,0,0)";
            ctx.fillRect(0,0,myCanW,myCanH);
            //裁剪一个圆形区域
            ctx.beginPath();
            ctx.translate(myCanW/2,myCanH/2);
            ctx.arc(0,0,myCanW/4,0,2*Math.PI);
            // ctx.stroke();
            ctx.clip();
            //开始绘制
            drawScreen()
            function drawScreen() {

                var toLoadImg = new Image();
                toLoadImg.onload  = onImageReady;
                toLoadImg.src ="src/img/1.jpg";

                function onImageReady(){
                    ctx.translate(-myCanW/2,-myCanH/2);//把笔触移动到左上角
                    var imgWidth = toLoadImg.width;
                    var imgHeight = toLoadImg.height;
                    // ctx.globalCompositeOperation = "destination-over";
                    // ctx.translate(100,100);
                    ctx.drawImage(toLoadImg,0,0,imgWidth, imgHeight,0,0,imgWidth,imgHeight);
                }
            }


        }
    </script>


    <button id="generalBtn">生成头像</button>
    <div>
        <canvas id="myCanvas2"></canvas>
    </div>
    <script>
        var myCanvas2 = document.getElementById('myCanvas2');
        var winW = window.innerWidth;
        myCanvas2.width = winW * .5;
        myCanvas2.height = winW * .5;
        
        ctx2 = myCanvas2.getContext("2d");
        var btn = document.getElementById("generalBtn");
        btn.addEventListener("click",function(e){
            let tmpImg = new Image();
            tmpImg.src = myCanvas.toDataURL();
            tmpImg.onload = function(){
                // document.body.appendChild(tmpImg);
                ctx2.drawImage(myCanvas,0,0,myCanvas.width,myCanvas.height,94,94,187,187);
            }
        })
    </script>
</body>

</html>